package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.enums.BiOperLogEnum;
import com.ruoyi.system.domain.Discount;
import com.ruoyi.system.domain.OperLog;
import com.ruoyi.system.domain.UserTb;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.framework.web.base.BaseController;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IDiscountService discountService;

    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private UserTbService userTbService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/user";
    }


    @GetMapping("/password")
    public String password()
    {
        return "/pages/manage/change-psw";
    }



//    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody JSONObject json)
    {
        //转换为user对象
        Integer pageNum = json.getInteger("pageNum")==null?1:json.getInteger("pageNum");
        Integer pageSize = json.getInteger("pageSize")==null?10:json.getInteger("pageSize");
        SysUser user = JSON.parseObject(json.toString(), SysUser.class);
        PageHelper.startPage(pageNum, pageSize, null);
        List<SysUser> list = userService.selectUserList(user);
        for (SysUser sysUser : list){
            //查询每个代理用户的折扣
            if (sysUser.getRoles().get(0).getRoleId() == 3){
                //查询折扣
                Discount discount = discountService.getDiscountByGameId(sysUser.getGameUserId());
                if (discount != null){
                    sysUser.setDiscount(discount.getPayDiscount()==null?new BigDecimal("0.8"):discount.getPayDiscount());
                }else {
                    sysUser.setDiscount(new BigDecimal("0.8"));
                }
                //查询当前剩余房卡和金币数量
                UserTb userTb = userTbService.selectGameUserById(sysUser.getGameUserId().intValue());
                sysUser.setGameUser(userTb);
            }
        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "user");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        return "/pages/manage/add";
    }

    /**
     * 新增保存用户（第一期为管理员）
     */
//    @RequiresPermissions("system:user:admin")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/addSave")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(@RequestBody JSONObject json)
    {
        Integer pageNum = json.getInteger("pageNum")==null?1:json.getInteger("pageNum");
        Integer pageSize = json.getInteger("pageSize")==null?10:json.getInteger("pageSize");
        SysUser user = JSON.parseObject(json.toString(), SysUser.class);
        PageHelper.startPage(pageNum, pageSize, null);
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId()))
        {
            return error("不允许修改超级管理员用户");
        }
        //校验登录名的唯一性
        Long count = userService.checkLoginNameUnique(user.getLoginName());
        if (count>0){
            return error("用户名重复");
        }
        user.setPassword(user.getPassword());
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setStatus(0);
        user.setLoginFlag(0);
        Long [] roleIds = new Long[]{2L};
        if (user.getRoleIds()==null){
            //默认添加为普通管理员
            user.setRoleIds(roleIds);
        }
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editSave(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId()))
        {
            return error("不允许修改超级管理员用户");
        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

//    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(String password,Long userId)
    {
        //重置密码
        SysUser sysUser = getSysUser();
//        if (sysUser.getLoginFlag() != 0 || sysUser.getRoles().get(0).getRoleId() != 2){
//            return error("业务出错");
//        }
        SysUser user = new SysUser();
        if (userId != null){
            user.setUserId(userId);
        }else {
            user.setUserId(sysUser.getUserId());
        }
        if (StringUtils.isNotEmpty(password)){
            user.setPassword(password);
        }else {
            user.setPassword("123456");
        }
        user.setLoginFlag(1);
        return toAjax(userService.resetUserPwd(user));
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwdByGameUserId")
    @ResponseBody
    public AjaxResult resetPwdByGameUserId(String password,Long gameUserId)
    {
       //先根据游戏id查询出该代理的系统账号
        SysUser sysUser = userService.selectUserByGameUserId(gameUserId);
        if (sysUser==null){
            return AjaxResult.error("该账号不是系统用户");
        }
        SysUser user = new SysUser();
        user.setUserId(sysUser.getUserId());
        if (StringUtils.isNotEmpty(password)){
            user.setPassword(password);
        }else {
            user.setPassword("123456");
        }
        return toAjax(userService.resetUserPwd(user));
    }


    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(String ids)
    {
        try
        {
            OperLog operLog = new OperLog();
            operLog.setType(BiOperLogEnum.DEL_ADMIN.getCode());
            operLog.setCreateBy(ShiroUtils.getLoginName());
            operLog.setCreateTime(new Date());
            return toAjax(userService.deleteUserByIds(ids,operLog));
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }



    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user)
    {
        return userService.checkEmailUnique(user);
    }
}